package m202405.d16;

/**
 * @@author: 爱做梦的锤子
 * @date: 2024/5/16 20:45
 */
public class Q416 {

    public static void main(String[] args) {
        Q416 q416 = new Q416();
        q416.canPartition(new int[]{1, 5, 11, 5});
    }

    /**
     * dp[i][j] 表示是否存在从数组[0,i]下标范围选取数的和等于j
     */
    public boolean canPartition(int[] nums) {
        if (nums.length < 2) {
            return false;
        }
        int sum = nums[0];
        int max = nums[0];
        for (int i = 1; i < nums.length; i++) {
            sum = sum + nums[i];
            max = Math.max(max, nums[i]);
        }
        int target = sum >> 1;
        if (sum % 2 != 0 || max > target) {
            return false;
        }
        boolean[][] dp = new boolean[nums.length][target + 1];
        for (int i = 0; i < nums.length; i++) {
            dp[i][0] = true;
        }
        dp[0][nums[0]] = true;
        for (int i = 1; i < nums.length; i++) {
            int num = nums[i];
            for (int j = 0; j <= target; j++) {
                if (j >= num) {
                    dp[i][j] = dp[i - 1][j] || dp[i - 1][j - num];
                } else {
                    dp[i][j] = dp[i - 1][j];
                }
            }
        }
        return dp[nums.length - 1][target];
    }
}
